/*
board-games:	An educational framework for board games programming.
    Copyright (C) 2008  Daniel Gutson, FuDePAN
    
    This file is part of board-games.

    board-games is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    board-games is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
*/

#include <exception>
#include <string>
#include <dlfcn.h>

class ShObj
{
    void* _handler;
    
public:
    struct Exception : std::exception
    {
        const std::string msg;
        
        Exception() : msg(dlerror()) {}
        ~Exception() throw() {}
        
        const char* what() const throw()
        {
            return msg.c_str();
        }
    };
    
    ShObj() : _handler(NULL) {}

    ~ShObj()
    {
        if (_handler != NULL)
            dlclose(_handler);
    }
    
    void load(const char* objname, int flag = RTLD_LAZY) throw(Exception)
    {
        _handler = dlopen(objname, flag);
        if (_handler == NULL)
            throw Exception();
    }
    
    template <class T> T load_func(const char* func_name) throw(Exception)
    {
        T ret = (T)(dlsym(_handler, func_name));
        
        if (dlerror() != NULL)
            throw Exception();
            
        return ret;
    }
};
